//
//  Utils.m
//  ChatDemo-UI2.0
//
//  Created by li.guibin on 15/11/30.
//  Copyright © 2015年 li.guibin. All rights reserved.
//

#import "Utils.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "sys/utsname.h"



static NSString *const HTTPAK = @"ztxh2017";//公钥
static NSString *const HTTPSK = @"U84Pmp7HTk7EdhGnWamRE7l6wDL";//私钥

#define openHttps NO

#define iOS7_or_Later ([[UIDevice currentDevice] systemVersion].floatValue >= 7.0 ? YES : NO)
static int _requestType;
static MBProgressHUD *HUD;

@implementation Utils

+ (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = NO;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = YES;
    
    //securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}

+(BOOL)get:(NSString *)urlStr parameters:(NSDictionary *)parameters success:(void (^)(NSInteger recode, id jsonObject))success failure:(void (^)(NSInteger recode, NSError *error))failure{
    
    //0.拼接请求的地址
    urlStr = [NSString stringWithFormat:@"%@%@",HOSTURL,urlStr ];
    
    //1.创建管理
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.声明返回结果的类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //3.如果报接受类型不一致请替换一致text/html  或者 text/plain
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    
    //4.设置请求超时时间
    manager.requestSerializer.timeoutInterval = 30;
    //5.请求
    [manager GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
  
        success(0,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(0,error);
        }
    }];
    return YES;
}
#pragma mark - 网络请求
+(BOOL)post:(NSString *)urlStr parameters:(NSMutableDictionary *)parameters success:(void (^)(NSInteger recode, id))success failure:(void (^)(NSInteger recode, NSError *))failure
{
    [Utils hideHUD];
   [Utils showHUD];
   urlStr = [NSString stringWithFormat:@"%@%@",HOSTURL,urlStr];
   
    NSAssert(urlStr != nil, @"ruquest address cannot be nil");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 30;
    [session.requestSerializer setValue:@"JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU" forHTTPHeaderField:@"DEVICEINFO"];
    
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    [session.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil]];
   
   [session POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
      
   } progress:^(NSProgress * _Nonnull uploadProgress) {
      
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
      [Utils hideHUD];
      
      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
      NSDictionary * dict = (NSDictionary *)responseObject;
      NSInteger recode = [[dict objectForKey:@"status"] integerValue];
       
      //数据返回失败提示
      if (recode != 1) {
          
               NSLog(@"------ error message :%@ %@，re_code:%ld",urlStr,[dict objectForKey:@"message"],(long)recode);
          
               return ;
          }
       
      //成功回调
         success(recode,responseObject);
      
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      
      [Utils hideHUD];
      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
      NSLog(@"----- error message:%@",[error localizedDescription]);
      
      if (failure) {
         failure(0,error);
      }
      
   }];

   return YES;
}

+ (void)POST:(NSString *)url parameters:(NSDictionary *)params constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    [Utils hideHUD];
    [Utils showHUD];
    url = [NSString stringWithFormat:@"%@%@",HOSTURL,url];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer setValue:@"JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU" forHTTPHeaderField:@"DEVICEINFO"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"text/plain", nil];
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        block(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 传输进度
        //        NSLog(@"%@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [Utils hideHUD];
        
        
        if ([responseObject isKindOfClass:[NSArray class]] || [responseObject isKindOfClass:[NSDictionary class]]) {
            success(responseObject);
        } else {
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);

            success([NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
    
}
+ (void)POSTApliy:(NSString *)url parameters:(NSDictionary *)params constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    [Utils hideHUD];
    [Utils showHUD];
    url = [NSString stringWithFormat:@"%@%@",HOSTURL,url];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer setValue:@"JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU" forHTTPHeaderField:@"DEVICEINFO"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"text/plain", nil];
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        block(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 传输进度
        //        NSLog(@"%@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [Utils hideHUD];
        
        
        if ([responseObject isKindOfClass:[NSArray class]] || [responseObject isKindOfClass:[NSDictionary class]]) {
            success(responseObject);
        } else {
//            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//            NSLog(@"%@",str);
            
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [Utils hideHUD];
        failure(error);
        
    }];
    
}
#pragma mark --- 获取当前时间戳--13位
+ (NSString *)getNowTime{
    
    //获取当前时间戳
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeSp = [NSString stringWithFormat:@"%.0f", time];
    
    return timeSp;
}

+(void)checkNetStateWithBlock:(void (^)(int type))block{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //status:
        
        //AFNetworkReachabilityStatusUnknown          = -1,  未知
        
        //AFNetworkReachabilityStatusNotReachable     = 0,   未连接
        
        //AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G
        
        //AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线连接
        
        //NSLog(@"%d", status);
        
        block(status);
    }];
    
}



+(void)showHUD
{
    AppDelegate *delegat = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    UIWindow *window = [delegat window];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([[self getCurrentVC] isKindOfClass:[UIViewController class]]) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self getCurrentVC].view animated:YES];
            
            HUD = hud;
        }else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
            HUD = hud;
        }

    });
}

+(void)hideHUD
{

    HUD.mode = MBProgressHUDModeIndeterminate;
    
    //HUD.labelText = @"加载完成";
    [HUD hide:YES afterDelay:0.6];
    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD removeFromSuperview];
    });
    
    HUD = nil;
}
//获取手机型号
+ (NSString*)deviceString
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
//    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
//    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
//    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
//    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
//    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
//    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
//    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
//    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
//    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
//    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
//    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
//    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
//    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
//    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
//    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
//    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
//
//    //iPod
//
//    if ([deviceString isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
//    if ([deviceString isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
//    if ([deviceString isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
//    if ([deviceString isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
//    if ([deviceString isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
//
//    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
//    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
//    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
//    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
//    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2 (32nm)";
//    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad mini (WiFi)";
//    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad mini (GSM)";
//    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad mini (CDMA)";
//
//    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3(WiFi)";
//    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3(CDMA)";
//    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3(4G)";
//    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
//    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4 (4G)";
//    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (CDMA)";
//
//    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air";
//    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
//    if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
//    if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
//    if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
//    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
//    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
//        NSLog(@"NOTE: Unknown device type: %@", deviceString);
    return deviceString;
}


+ (NSString *)getTransactionId{
    NSMutableString * originalStr = [NSMutableString stringWithString:[[NSUUID UUID] UUIDString]];
    [originalStr replaceOccurrencesOfString:@"-" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [originalStr length])];

    return [originalStr lowercaseString];
}





+ (void)alertViewWithMessage:(NSString *)message{
    
    UIAlertView * view  = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [view show];
}



+ (NSString *)getStringByDate:(NSDate *)date{
    if (date == nil) {
        return nil;
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    return currentDateStr;
}

+ (NSString*)URLencode:(NSString *)originalString stringEncoding:(NSStringEncoding)stringEncoding {
    NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                            @"@" , @"&" , @"=" , @"+" ,    @"$" , @"," ,
                            @"!", @"'", @"(", @")", @"*", nil];
    
    NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F", @"%3F" , @"%3A" ,
                             @"%40" , @"%26" , @"%3D" , @"%2B" , @"%24" , @"%2C" ,
                             @"%21", @"%27", @"%28", @"%29", @"%2A", nil];
    
    NSUInteger len = [escapeChars count];
    
    NSMutableString *temp = [[originalString
                               stringByAddingPercentEscapesUsingEncoding:stringEncoding]
                              mutableCopy];
    
    int i;
    for (i = 0; i < len; i++) {
        [temp replaceOccurrencesOfString:[escapeChars objectAtIndex:i]
                              withString:[replaceChars objectAtIndex:i]
                                 options:NSLiteralSearch
                                   range:NSMakeRange(0, [temp length])];
    }
    
    NSString *outStr = [NSString stringWithString:temp];
    
    return outStr;
}

+(NSString *) encodeUrlStr:(NSString *)sourceString
{
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                  NULL,
                                                                                  (CFStringRef)sourceString,
                                                                                  NULL,
                                                                                  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                  kCFStringEncodingUTF8 ));
    return encodedString;
}


+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
+ (NSUInteger)transformStringToNsinterger:(NSString *)dateStr
{
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *fromdate=[format dateFromString:dateStr];
    NSInteger frominterval = [fromdate timeIntervalSince1970];
    return frominterval;
}
+(void)hasMobile:(id)delegate andFunc:(NSString *)func{
    
    NSString *message = [NSString stringWithFormat:@"%@是高级功能,请先绑定您的手机号",func];
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:delegate cancelButtonTitle:@"取消" otherButtonTitles:@"绑定手机号", nil];
    [alert show];
    return;

}

+(UIImage *)imageWithImage:(UIImage *)orgImage{
    
    //原始图片的尺寸
    CGSize oldSize = orgImage.size;
    
    //原始图片的宽度
    CGFloat oldW = oldSize.width;
    
    //原始图片的高度
    CGFloat oldH = oldSize.height;
    
    //新的图片尺寸
    CGSize size = CGSizeMake(oldW, oldH);
    
    //宽和高之中的大值
    CGFloat bigF = oldW>oldH?oldW:oldH;
    
    //宽高比例
    CGFloat scale = (float)oldW/oldH;
    if (bigF > 300) {
        
        if (bigF == oldW) {
            
            oldW = 300;
            oldH = oldW/scale;
            size = CGSizeMake(oldW, oldH);
            
        }else if(bigF == oldH){
            
            oldH = 300;
            oldW = oldH * scale;
            size = CGSizeMake(oldW, oldH);
        }
        
    }
    
    
    UIImage *newImage = nil;
    CGSize imageSize = size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [orgImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}

//判断是否含有表情
+ (BOOL)stringContainsEmoji:(NSString *)string{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}




+(CGSize)labelSizeWithStr:(NSString *)str andWidth:(CGFloat)width andFont:(CGFloat)font{
    
    CGSize oriSize = CGSizeMake(width, 10000);
    
    CGSize size = [str boundingRectWithSize:oriSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return size;
}

+(CGFloat)resizeContentLabelHeightWithString:(NSString *)str andLineSpacing:(CGFloat)space andFont:(UIFont *)font andMaxWidth:(CGFloat)maxWidth{
    
    NSStringDrawingOptions opt = NSStringDrawingUsesLineFragmentOrigin;
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:space];
    
    NSDictionary *att = @{NSFontAttributeName: font,NSParagraphStyleAttributeName:style};
    
    CGSize maxSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    
    CGSize size = [str boundingRectWithSize:maxSize
                                    options:opt
                                 attributes:att
                                    context:nil].size;
    return size.height;
}

//// 计算字符串尺寸
//+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize lineBreakMode:(NSLineBreakMode)lineBreakMode
//{
//    CGSize actualSize = CGSizeZero;
////    if ([self isEmpty:text]) {
////        return actualSize;
////    }
//    
//    if (iOS7_or_Later) {
//        actualSize = [text boundingRectWithSize:maxSize
//                                        options:NSStringDrawingUsesLineFragmentOrigin
//                                     attributes:@{NSFontAttributeName: font}
//                                        context:nil].size;
//    }else {
//        actualSize = [text sizeWithFont:font
//                      constrainedToSize:maxSize lineBreakMode:lineBreakMode];
//    }
//    return actualSize;
//}

+(NSString *)getProperDataStringWithString:(NSString *)str{
   
   NSLog(@"str = %@",str);
    if (!str||str.length == 0) {
        
        return nil;
    }
    
    NSString *oristr = str;
    
    if (str.length > 10) {  //2016-07-23 09:12
        str = [str substringToIndex:10];
    }
    
    NSDate *nowDate = [NSDate date];
    
    NSTimeInterval perDate = 24 * 60 * 60;
    //NSTimeInterval yearDate = 24 * 60 * 60 * 365;
    
    NSDate *yesterday;
    yesterday = [nowDate dateByAddingTimeInterval: -perDate];
    
    //NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    
    NSString *dayString = [[nowDate description] substringToIndex:10];
    NSString * yearString = [[nowDate description] substringToIndex:4];
    
    //1.先判断是否是今年
    NSString *nowYear = [str substringToIndex:4];
    
    if (![yearString isEqualToString:nowYear]) {
        
        return str;
    }
    
    if (![str isEqualToString:dayString]) {
        
        oristr = [oristr substringFromIndex:5];

        return oristr;
    }
    
    if (oristr.length > 11) {
        
        
        return [oristr substringFromIndex:11];
        
    }else{
        
        return oristr;
    }
}

+(NSString *)getDataStringWithoutSecondString:(NSString *)str{
    
    if (!str) {
        
        return nil;
    }
    
    NSString *dayStr;
    if (str.length > 16) {  //2016-07-23 09:12
        str = [str substringToIndex:16];
        dayStr = [str substringToIndex:10];
        
    }
    
    
    NSDate *nowDate = [NSDate date];
    
    NSTimeInterval perDate = 24 * 60 * 60;
    //NSTimeInterval yearDate = 24 * 60 * 60 * 365;
    
    NSDate *yesterday;
    yesterday = [nowDate dateByAddingTimeInterval: -perDate];
    
    //NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    
    NSString *dayString = [[nowDate description] substringToIndex:10];
    NSString * yearString = [[nowDate description] substringToIndex:4];
    
    //1.先判断是否是今年
    NSString *nowYear = [str substringToIndex:4];
    
    if (![yearString isEqualToString:nowYear]) {
        
        return str;
    }
    
    if (![dayStr isEqualToString:dayString]) {
        
        str = [str substringFromIndex:5];
        
        return str;
    }else
    {
        if (str.length > 11) {
            
            
            return [str substringFromIndex:11];
            
        }else{
            
            return str;
        }
    }
   
}

+(NSString *)getDataStringWithString:(NSString *)str{
    
    if (!str) {
        
        return nil;
    }
    
    if (str.length > 16) {  //2016-07-23 09:12
        str = [str substringToIndex:16];
    }
    
    NSDate *nowDate = [NSDate date];

    NSString * yearString = [[nowDate description] substringToIndex:4];
    
    //1.先判断是否是今年
    NSString *nowYear = [str substringToIndex:4];
    
    if (![yearString isEqualToString:nowYear]) {
        
        return str;
    }else
    {
        return [str substringFromIndex:5];
    }
  
}



+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        //alertView的话 获取不到返回nil
        if ([window subviews].count == 0) {
            return nil;
        }
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

+ (NSString *)getCurrentTime {
    
    NSDate *date = [NSDate date]; // 获得时间对象
//    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
//    NSTimeInterval time = [zone secondsFromGMTForDate:date];// 以秒为单位返回当前时间与系统格林尼治时间的差
//    NSDate *dateNow = [date dateByAddingTimeInterval:time];// 然后把差的时间加上,就是当前系统准确的时间
    NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
    
    [forMatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateStr = [forMatter stringFromDate:date];
    
    return dateStr;
}



+ (BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    
    return NO;
    
}

+ (void)clearWebViewCache{
    
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];

}


UIColor* colorFromHex(NSString * hexString){
    UIColor *color = colorFromHexAndAlpha(hexString, 1.0);
    return color;
}

UIColor* colorFromHexAndAlpha(NSString * hexString,CGFloat alpha){
    unsigned int hexInt = 0;
    // Create scanner
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    // Tell scanner to skip the # character
    [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
    // Scan hex value
    [scanner scanHexInt:&hexInt];
    
    // Create color object, specifying alpha as well
    UIColor *color =
    [UIColor colorWithRed:((CGFloat) ((hexInt & 0xFF0000) >> 16))/255
                    green:((CGFloat) ((hexInt & 0xFF00) >> 8))/255
                     blue:((CGFloat) (hexInt & 0xFF))/255
                    alpha:alpha > 1.0 ? 1.0 : alpha];
    
    return color;
}

#pragma mark 16位色值转颜色
//使用方法，传入字符串格式@"#XXXXXX"
+(UIColor *)stringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 charactersif ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appearsif ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


//关联词搜索
+(NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText
{
    NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:20];
    if (findText == nil && [findText isEqualToString:@""]) {
        return nil;
    }
    NSRange rang = [text rangeOfString:findText];
    if (rang.location != NSNotFound && rang.length != 0) {
        [arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];
        NSRange rang1 = {0,0};
        NSInteger location = 0;
        NSInteger length = 0;
        for (int i = 0;; i++)
        {
            if (0 == i) {
                location = rang.location + rang.length;
                length = text.length - rang.location - rang.length;
                rang1 = NSMakeRange(location, length);
            }else
            {
                location = rang1.location + rang1.length;
                length = text.length - rang1.location - rang1.length;
                rang1 = NSMakeRange(location, length);
            }
            rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
            if (rang1.location == NSNotFound && rang1.length == 0) {
                break;
            }else
                [arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
        }
        return arrayRanges;
    }
    return nil;
}



+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}


+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
   
   NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
   
   NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   
   NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
   
   [calendar setTimeZone: timeZone];
   
   NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
   
   NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
   
   return [weekdays objectAtIndex:theComponents.weekday];
   
}

+ (void)starageData:(NSDictionary *)dictionary{
    
    NSString * userid = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"id"]];
    NSString * token = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"token"]];
    NSString * username = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"username"]];
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    [db setValue:userid forKey:@"uid"];
    [db setValue:token forKey:@"token"];
    [db setValue:username forKey:@"username"];
    [db synchronize];
}

+ (NSString *)time_timestampToString:(NSString *)timesStr{
    
    NSInteger timestamp = [timesStr integerValue];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
    
    [dateFormat setDateFormat:@"yyyy.MM.dd HH:mm"];
    
    NSString* string=[dateFormat stringFromDate:confromTimesp];
    
    return string;
    
}

+ (NSString *)time_timestampToString2:(NSString *)timesStr{
    
    NSInteger timestamp = [timesStr integerValue];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
    
    [dateFormat setDateFormat:@"yyyy.MM.dd"];
    
    NSString* string=[dateFormat stringFromDate:confromTimesp];
    
    return string;
    
}

@end
